let VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main(){\n' +
  'gl_Position = a_Position;\n' +
  'gl_PointSize = 8.0;\n' +
  '}\n';
let FSHADER_SOURCE =
  'precision mediump float;\n' +
  'void main(){\n' +
  'gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n' +
  '}\n';

const initVertexBuffers = (gl) => {
  //data
  let vertices = new Float32Array([-0.5, 0.5, 0.1, 0.2, 0.3, -0.5, -0.5, 0.1, 0.4, 0.3,
    0.5, -0.5, 0.2, 0.1, 0.8,
    0.5, 0.5, 0.7, 0.4, 0.3,

    -0.3, 0.3, 0.6, 0.5, 0.4, -0.3, -0.3, 0.6, 0.5, 0.4,
    0.3, -0.3, 0.6, 0.5, 0.4,
    0.3, 0.3, 0.6, 0.5, 0.4
  ]);
  let indices = new Uint16Array([
    0, 1, 2, 2, 0, 3,
    4, 5, 6, 6, 4, 7
  ]);
  let n = indices.length;
  let FSIZE = vertices.BYTES_PER_ELEMENT;

  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
  gl.clearColor(0.9, 0.9, 0.9, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);

  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.DYNAMIC_DRAW);

  let a_Positionaddr = gl.getAttribLocation(gl.program, 'a_Position');
  let a_Coloraddr = gl.getAttribLocation(gl.program, 'a_Color');

  gl.vertexAttribPointer(a_Positionaddr, 2, gl.FLOAT, false, 0, 0);

  gl.enableVertexAttribArray(a_Positionaddr);
  gl.enableVertexAttribArray(a_Coloraddr);

  gl.drawElements(gl.POINTS, n, gl.UNSIGNED_SHORT, 0);
  let data = [];
  for (let i = 0; i < 10; i++) {
    if (Math.random() < 0.5) {
      data.push((-1) * Math.random());
    } else {
      data.push(Math.random());
    }
  }
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.DYNAMIC_DRAW);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 3, 4]), gl.DYNAMIC_DRAW);
  gl.drawElements(gl.POINTS, data.length / 2, gl.UNSIGNED_SHORT, 0);
}

let canvas = document.getElementById('webgl');
let gl = getWebGLContext(canvas);
if (!gl) {
  console.log('Failed to get the rendering context for WebGL');
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
  console.log('Failed to initialize shaders');
}

let n = initVertexBuffers(gl);
if (n < 0) {
  console.log('Failed to set the positon of vertices.');
}